package com.salt.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.salt.config.AliyunSmsConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 短信服务工具类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SmsUtil {

    private final AliyunSmsConfig smsConfig;
    
    /**
     * 发送验证码
     *
     * @param mobile 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String mobile, String code) {
        try {
            // 创建DefaultAcsClient实例并初始化
            DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                smsConfig.getAccessKeyId(),
                smsConfig.getAccessKeySecret()
            );
            IAcsClient client = new DefaultAcsClient(profile);
            
            // 组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);
            request.setSignName(smsConfig.getSignName());
            request.setTemplateCode(smsConfig.getTemplateCode());
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            
            // 发送短信
            SendSmsResponse response = client.getAcsResponse(request);
            if (response.getCode() != null && response.getCode().equals("OK")) {
                log.info("短信发送成功: {}", mobile);
                return true;
            } else {
                log.error("短信发送失败: {}, {}", mobile, response.getMessage());
                return false;
            }
        } catch (Exception e) {
            log.error("短信发送异常", e);
            return false;
        }
    }
} 